
<?php

class UserController extends BaseController {

    /**
     * The layout that should be used for responses.
     */
    protected $layout = 'layouts.master';

	const GLOBAL_MESSAGE = 'global';
    /**
     * Show the user profile.
     */
    public function login()
    {
        $this->layout->content = View::make('login');
    }


    public function postSignin()
    {
       // App::setLocale('zh_cn'); 

        $validator = Validator::make(Input::all(), array(
          'email'        =>'required|email',
          'password'        =>'required'
        ));


      if($validator->fails() ){
        return Redirect::route('login')
                         ->withErrors($validator)
                         ->withInput();
     }else{


            $remmeber = (Input::has('remmeber'))?true:false;
            $auth = Auth::attempt(array(
                'email'     =>  Input::get('email'),
                'password'   =>  Input::get('password'),
                'active'     =>  1
                ),$remmeber);

            if($auth){

                return Redirect::intended('/');
            }else
            {
                 return Redirect::route('login')->with(self::GLOBAL_MESSAGE,trans('messages.PasswrodWrongorNotActive'));
 
            }

     }
       return Redirect::route('login')->with(self::GLOBAL_MESSAGE,'there is a problem sign you in ,have you activate?');
    } 


      public function signup()
	  
    {
	
	 //   $settings = parse_ini_file(app_path()."\config\GLOBALS.ini",true);
  //      if( $settings)
	 //   {
		//    $emails =  $settings['allow_Email']['email'];
		//    $data = ['emails'=>$emails] ; 
		// }

       $networks = DB::table('network')->orderBy('school', 'asc')->get();
       $data['networks'] =   $networks;


        $this->layout->content = View::make('signup',$data);
    }


   public function postSignup(){

        $schooldomain = Input::get("schoolname");
        $email = Input::get("email");
        $fullemail =  $email.$schooldomain;       
     

      $input  =  array(
          'email'           => $fullemail,
          'password'        => Input::get('password'),
          'password_again'  => Input::get('password_again'),
        );

      $validator =  array(
          'email'           =>'email|required|max:30|unique:users',
          'password'        => array('required','regex:/^(?=.*\d)(?=.*[a-zA-Z]).{8,}$/'),
          'password_again'  =>'required|same:password',
        );
   
   
    $validator = Validator::make($input,$validator);
    if($validator->fails() ){
        return Redirect::route('signup')
                         ->withErrors($validator)
                         ->withInput();
    }else{

        $password = Input::get("password");
        $code = str_random(60);

        $user = User::create(array(
            'code'      => $code    ,
            'password'  => Hash::make($password),
            'email'     => $fullemail,
            'active'    =>  0
            ));
    }

    if($user){
  
        $data = array('url'=>URL::route('activate',$code));
        Mail::send('emails.welcome_emailtemplate', $data , function($message) use ($user) {
             $message->to( $user->email, $user->username)->subject('Welcome to twoPLUGS');
        });

        return Redirect::route('home')
                        ->with(self::GLOBAL_MESSAGE,trans('messages.AccountCreatedActiveEmailSend'));
   }else{
        return Redirect::route('signup')
        ->with(self::GLOBAL_MESSAGE,"your account can not been created pealse try later");
   }


}



   public function signout()
    {
        Auth::logout();
       return Redirect::route('home');

    }

   public function rtpass()
    {
        $this->layout->content = View::make('rtpass');
    }

   public function postRtpass(){

      $rules = array(
            'oldpassword' => array('required','min:8', 'regex:/^(?=.*\d)(?=.*[a-zA-Z]).{8,}$/'),
            'newpassword' => array('required','min:8', 'regex:/^(?=.*\d)(?=.*[a-zA-Z]).{8,}$/'),
            'confirmpassword' => array('required','min:8', 'same:newpassword','regex:/^(?=.*\d)(?=.*[a-zA-Z]).{8,}$/'),
     );
   
   
   $validator = Validator::make(Input::all(), $rules);
    if($validator->fails() ){
        return Redirect::route('rtpass')->withErrors($validator);
                 
    }else{

      $user = User::find(Auth::user()->id);
      $oldpassword = Input::get('oldpassword');
      $password = Input::get('newpassword');
  
       if(Hash::check( $oldpassword ,$user->getAuthPassword())){
            $user->password = Hash::make($password);
         if($user->save()){

          return Redirect::route('home')->with(self::GLOBAL_MESSAGE,'password change thank you ');
         }

       }
        
   }
       return Redirect::route('home')->with(self::GLOBAL_MESSAGE,'your password could not been changed');
   }


    public function home()
    {

       $pics = Company::getCompanyPics(2);
     //  dd($pics['maxcompanypics']);
      // dd($pics['picsnumber']);
      //dd($pics['pics']);


      // dd( DB::table('network')->get());
      $networks = DB::table('network')->get();
       //$emails = array_pluck($networks, 'domain');

      $data['networks'] =   $networks;
       //App::setLocale('zh_cn'); 
      //dd($emails);   
       
       $this->layout->content = View::make('home',$data);
    }




   public function activate($code)
    {

       $user = User::where("code","=",$code)
                    ->where("active","=",0);
   
      if($user->count()){


        $user = $user->first();
        $user->active = 1;
        $user->code = '';
        $user->save();
        if($user->save()){

        $profile = Profile::create(array(
            'user_id'      =>  $user->id    ,
            'network_id'  => Network::getNetWorkIDByDomain($user->email),
         ));

          if($profile){
         
          Auth::login($user);

       //  return Redirect::action('ProfileController@profile')->with(self::GLOBAL_MESSAGE,trans('messages.ActivedYourAccount'));


        return Redirect::route('profile', $user->id)->with(self::GLOBAL_MESSAGE,trans('messages.ActivedYourAccount'));
          }
        
        }
      }

        return Redirect::route('home')->with(self::GLOBAL_MESSAGE,'we can not activate your account  please try later');
    }



    
     public function forgot(){

        $this->layout->content = View::make('forgot');

     }

     public function postForgot()
    {


          $validator = Validator::make(Input::all(), array(
          'email'           =>'required|email'
          
        ));
         if($validator->fails() ){
        return Redirect::route('forgot')
                         ->withErrors($validator)
                         ->withInput();
    }else{

     $user = User::where('email','=',Input::get('email'));
     if($user->count())
     {
         $user = $user->first();
          $code= str_random(60);
          $passworde= str_random(10);

          $user->code  = $code;
          $user->password_temp  =  Hash::make($passworde);
          if($user->save()){

              //create a view to send email
            $data = array('username' =>$user->username ,'password' =>$passworde,'url'=>URL::route('recover',$code));
              Mail::send('emails.forgot_emailtemplate', $data , function($message) use ($user) {
                $message->to( $user->email, $user->username)->subject('Password Reset');
             });             
                return Redirect::route('home')->with(self::GLOBAL_MESSAGE,trans('messages.CheckEamilResetPassword'));
          }
           else
            {
              return Redirect::route('forgot')->with(self::GLOBAL_MESSAGE,'kk');
            }
      }
        return Redirect::route('forgot')->with(self::GLOBAL_MESSAGE,trans('messages.postForgotNoAccoutReg'));
    }

}





public function recover($code){

  $user = User::where('code','=',$code)
                  ->where('password_temp','!=','');

    if($user->count()){
      $user=$user->first();
  
  $user->password   = $user->password_temp;
  $user->password_temp = '';
  $user->code          = '';

  if($user->save()){

   $data = array('username' =>$user->username);
              Mail::send('emails.confirm_email_change_template', $data , function($message) use ($user) {
                $message->to( $user->email, $user->username)->subject('Your twoPLUGS password has been changed');
             });    
      return Redirect::route('rtpass')->with(self::GLOBAL_MESSAGE,trans('messages.PasswordReset'));
  }
       return Redirect::route('home')->with(self::GLOBAL_MESSAGE,'you can not recover your account ');

    }
}


        public function sendEmail($name)
    {

        $data = $arrayName = array('name' =>$name );
        Mail::send('emails.welcome_emailtemplate', $data , function($message) {
             $message->to('koni.zhang@gmail.com', 'Koni Zhang')->subject('Welcome');
        });
     
        return "twoPLUGS".$name;
    }


}